<?php

namespace App\Http\Controllers\Home;

use App\Http\Models\Admin\Product;
use App\Http\Models\Admin\ProductCategory;
use App\Http\Requests\Home\ProductionIndexRequest;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ApiResponser;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class ProductionController extends Controller
{
    use ApiChecker,ApiResponser;

    /**
     * Display a listing of the resource.
     *
     * @param ProductionIndexRequest $request
     * @return \Illuminate\Http\Response
     * @throws \App\Exceptions\AdminManageException
     */
    public function index(ProductionIndexRequest $request)
    {
        if ($request->product_category_id) {

            /** @var ProductCategory $product_category */
            $product_category = ProductCategory::find($request->product_category_id);
                $this->checkItemExist($product_category, '产品种类');

            $production = $product_category->products()
                ->filterKeyWord($request->keyword)
                ->latest('sort')
                ->paginate($request->per_page?:15);

        } else {  // 搜索标题或者型号

            $production = Product::filterKeyWord($request->keyword)
                ->latest('sort')
                ->paginate($request->per_page?:15);

        }

        return $this->response(compact('production'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $product_categories = ProductCategory::where('super_id', ProductCategory::TOP_CATEGORY)
            ->with('getSubCategories')
            ->latest('priority')
            ->get();

        return $this->response(compact('product_categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }
    
    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     * @throws \App\Exceptions\AdminManageException
     */
    public function show($id)
    {
        $product = ProductCategory::find($id);
            $this->checkItemExist($product, '产品');

        return $this->response(compact('product'));
    }

}
